#include "widget.h"
#include "ui_widget.h"

#include <QAbstractSocket>
#include <QMessageBox>
#include <QNetworkInterface>
#include <QTcpSocket>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setLayout(ui->verticalLayout);
    server = new QTcpServer(this);

    connect(server, SIGNAL(newConnection()),this,SLOT(on_newClient_connect()));
    connect(ui->comboBoxChlidren,&MyComboBox::on_ComboBox_clicked,this,&Widget::mComboBox_reflesh);

    ui->btnStopListen->setEnabled(false);
    ui->btnLineOut->setEnabled(false);
    ui->btnSend->setEnabled(false);

    QList<QHostAddress> address = QNetworkInterface::allAddresses();//存储所有地址
    for(QHostAddress tmp : address){
        if(tmp.protocol() == QAbstractSocket::IPv4Protocol){
            ui->comboBoxAddr->addItem(tmp.toString());
        }

    }



}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_newClient_connect()
{
    if(server->hasPendingConnections()){
        QTcpSocket* connection = server->nextPendingConnection();
        qDebug() << "client Addr: " << connection->peerAddress().toString() << "client Port: " << connection->peerPort();//客户端信息
        ui->textEditRev->insertPlainText("客户端地址: " + connection->peerAddress().toString() +
                                         "  客户端端口号: " + QString::number(connection->peerPort()) + "\n");

        connect(connection,SIGNAL(readyRead()),this,SLOT(on_readyread_handler()));//读取客户端发送的信息
        //connect(connection,SIGNAL(disconnected()),this,SLOT(mdisconnected()));//客户端断开链接信号和槽
        connect(connection,SIGNAL(stateChanged(QAbstractSocket::SocketState ))
                ,this,SLOT(mstateChanged(QAbstractSocket::SocketState )));

        ui->comboBoxChlidren->addItem(QString::number(connection->peerPort()));
        ui->comboBoxChlidren->setCurrentText(QString::number(connection->peerPort()));

        if(!ui->btnSend->isEnabled()){
            ui->btnSend->setEnabled(true);
        }
    }


}


void Widget::on_btnListen_clicked()
{
    //QHostAddress addr("192.168.0.104");//构造一个IP地址
    int port = ui->lineEditProt->text().toInt();
    //if(!server->listen(QHostAddress::Any,port)){
    if(!server->listen(QHostAddress(ui->comboBoxAddr->currentText()),port)){
        QMessageBox msgBox;
        msgBox.setWindowTitle("监听失败");
        msgBox.setText("端口号被占用");
        msgBox.exec();
        qDebug() << "listen Error!";
        return ;
    }
    ui->btnListen->setEnabled(false);
    ui->btnLineOut->setEnabled(true);
    ui->btnStopListen->setEnabled(true);
}

void Widget::on_readyread_handler()
{
    QTcpSocket* tmpSock = qobject_cast<QTcpSocket*>(sender());
    QByteArray revData = tmpSock->readAll();
    ui->textEditRev->moveCursor(QTextCursor::End);
    ui->textEditRev->ensureCursorVisible();
    ui->textEditRev->insertPlainText("\n客户端: " + revData);


}

void Widget::mdisconnected()
{
    QTcpSocket* tmpSock = qobject_cast<QTcpSocket*>(sender());
    qDebug() << "client out!";
    ui->textEditRev->insertPlainText("客户端断开！");
    tmpSock->deleteLater();
}

void Widget::mstateChanged(QAbstractSocket::SocketState socketState)
{
    int tmpIndex;
    QTcpSocket* tmpSock = qobject_cast<QTcpSocket*>(sender());
    qDebug() << "client out! In state:" << socketState;
    switch (socketState) {
        case QAbstractSocket::UnconnectedState:
            ui->textEditRev->insertPlainText("客户端断开！");
            tmpIndex = ui->comboBoxChlidren->findText(QString::number(tmpSock->peerPort()));
            ui->comboBoxChlidren->removeItem(tmpIndex);
            tmpSock->deleteLater();
            if(ui->comboBoxChlidren->count() == 0){
                ui->btnSend->setEnabled(false);
            }

            break;
        case QAbstractSocket::ConnectingState: ui->textEditRev->insertPlainText("客户端接入！");break;

    }
}


void Widget::on_btnSend_clicked()
{
    QList<QTcpSocket*> tcpSocketClient = server->findChildren<QTcpSocket*>();
    if(tcpSocketClient.isEmpty()){
        QMessageBox msgBox;
         msgBox.setText("当前无连接！");
         msgBox.setWindowTitle("发送错误！");
         msgBox.exec();
         ui->btnSend->setEnabled(false);
         return;
    }
    if(ui->comboBoxChlidren->currentText() != "ALL"){   //如果选all就全发送，否则就指定chlidIndex发送
        QString currentName = ui->comboBoxChlidren->currentText();
        for(auto tmp : tcpSocketClient){
            if(QString::number(tmp->peerPort()) == currentName){
                tmp->write(ui->textEditSend->toPlainText().toStdString().c_str());
            }
        }

    }else{
        for(auto tmp : tcpSocketClient){
            if(tmp){
                tmp->write(ui->textEditSend->toPlainText().toStdString().c_str());
            }
        }
    }


}

void Widget::mComboBox_reflesh()//刷新客户端在ComboBoxChlidren里
{
    ui->comboBoxChlidren->clear();
    QList<QTcpSocket*> tcpSocketClients = server->findChildren<QTcpSocket*>();
    for(auto tmp : tcpSocketClients){
        if(tmp){
            ui->comboBoxChlidren->addItem(QString::number(tmp->peerPort()));
        }
    }
    ui->comboBoxChlidren->addItem("ALL");
}




void Widget::on_btnStopListen_clicked()
{
    QList<QTcpSocket*> tcpSocketClients = server->findChildren<QTcpSocket*>();
    for(auto tmp : tcpSocketClients){
        if(tmp){
            tmp->close();
        }
    }
    server->close();
    ui->btnListen->setEnabled(true);
    ui->btnLineOut->setEnabled(false);
    ui->btnStopListen->setEnabled(false);
}

void Widget::on_btnLineOut_clicked()
{
    on_btnStopListen_clicked();
    delete server;
    this->close();
}
